<template lang="">
  <div class="location">
    <div class="serach">
      <van-search
        placeholder="搜索"
        v-model="keyword"
        @input="search"
      ></van-search>
      <ul class="search_content">
        <li
          v-for="(item, index) in searchList"
          :key="index"
          @click="itemClick(item)"
        >
          {{ item.name }}
        </li>
      </ul>
    </div>
    <div id="container"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      keyword: "",
      searchList: [],
      city: "",
    };
  },
  methods: {
    search() {
      var that = this;
      AMap.plugin("AMap.Autocomplete", function () {
        // 实例化Autocomplete
        var autoOptions = {
          //city 限定城市，默认全国
          city: that.city,
        };
        var autoComplete = new AMap.Autocomplete(autoOptions);
        autoComplete.search(that.keyword, function (status, result) {
          // 搜索成功时，result即是对应的匹配数据
          console.log(result);
          that.searchList = result.tips;
        });
      });
    },

    itemClick(item) {
      this.$store.commit("updateLocaltion", item);
      this.$router.push("/home");
    },
  },
  mounted() {
    var map = new AMap.Map("container");

    var that = this;
    if (this.$store.state.locationAddress.name) {
      this.city = this.$store.state.locationAddress.name;
      var map = new AMap.Map("container", {
        zoom: 16, //级别
        center: [
          that.$store.state.locationAddress.location.lng,
          that.$store.state.locationAddress.location.lat,
        ], //中心点坐标
      });
      var marker = new AMap.Marker({
        position: [
          that.$store.state.locationAddress.location.lng,
          that.$store.state.locationAddress.location.lat,
        ], //位置
      });
      map.add(marker); //添加到地图
    } else {
      AMap.plugin("AMap.CitySearch", function () {
        var citySearch = new AMap.CitySearch();
        citySearch.getLocalCity(function (status, result) {
          if (status === "complete" && result.info === "OK") {
            // 查询成功，result即为当前所在城市信息
            console.log(result);
            that.city = result.city;
          }
        });
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.location {
  height: 100vh;
  .serach {
    height: calc(100% - 246px);
  }
  .search_content {
    height: calc(100% - 54px);
    overflow: scroll;
    li {
      padding: 12px 10px;
    }
  }
}
#container {
  width: 100%;
  height: 200px;
}
</style>
